<template>
  <div class="password-page">
    <button class="back-btn" @click="$router.back()">返回</button>
    <h2>修改密码</h2>
    <div>
      <label>原密码：</label>
      <input v-model="oldPassword" type="password" />
    </div>
    <div>
      <label>新密码：</label>
      <input v-model="newPassword" type="password" />
    </div>
    <button @click="changePassword">提交</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      oldPassword: '',
      newPassword: '',
      username: ''
    }
  },
  created() {
    // 获取当前用户名
    this.$axios.get('/user').then(res => {
      this.username = res.data.username;
    });
  },
  methods: {
    changePassword() {
      if (!this.oldPassword || !this.newPassword) {
        this.$message.error('请输入原密码和新密码');
        return;
      }
      if (this.oldPassword === this.newPassword) {
        this.$message.error('新密码不能与原密码相同');
        return;
      }
      // 先校验原密码是否正确
      this.$axios.post('/auth', {
        username: this.username,
        password: this.oldPassword
      }).then(loginRes => {
        console.log(loginRes);
        if (loginRes.status === 200) {
          // 原密码正确，调用修改密码接口
          this.$axios.post('/password', {
            username: this.username,
            password: this.newPassword
          }).then(res => {
            if (res.data === 'Update the password successfully.' || res.data.success) {
              this.$router.back();
            } else {
              alert('密码修改失败');
            }
          });
        } else {
          alert('原密码错误');
        }
      });
    }
  }
}
</script>

<style scoped>
.password-page {
  max-width: 400px;
  margin: 60px auto;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
}

.back-btn {
  background: #6c757d;
  color: #fff;
  border: none;
  padding: 8px 18px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 18px;
}

.password-page label {
  display: block;
  margin-bottom: 8px;
}

.password-page input {
  width: 100%;
  margin-bottom: 16px;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.password-page button {
  background: #0097FF;
  color: #fff;
  border: none;
  padding: 10px 24px;
  border-radius: 4px;
  cursor: pointer;
}
</style>